package 多线程;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // LinkedBlockingQueue
        Executors.newFixedThreadPool(1);
        Executors.newSingleThreadExecutor();
        // Integer.MAX_VALUE
        Executors.newCachedThreadPool();

        // 七大参数
        int corePoolSize = 3;
        int maximumPoolSize = 9;
        long keepAliveTime = 30;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(9);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
        // 两种提交任务的方式
        Runnable runnable = () -> {
            System.out.println("hello");
        };
        //1
        pool.execute(runnable);
        // 2.1
        pool.submit(runnable);
        Callable<String> callable = ()->{
            return "hello";
        };
        // 2.2
        Future<String> future1 = pool.submit(runnable, "666");
        System.out.println("future1 = " + future1.get());
        // 2.3
        Future<String> future2 = pool.submit(callable);
        System.out.println("future2 = " + future2.get());
        // 两种关闭线程池的方式
        // 1.1 不在接受任务,队列里面的任务结束后自然关闭
        pool.shutdown();
        //
//        pool.shutdownNow();
    }
}
